﻿using huqiang;
using huqiang.Communication;
using huqiang.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Win_LogServer
{
    public partial class MainForm : Form
    {
        KcpServer<KcpUser> kcp;
        public MainForm()
        {
            InitializeComponent();
            Thread.CurrentThread.IsBackground = true;
            this.SizeChanged += ReSized;
            this.richTextBox1.Size = ClientSize;
            this.richTextBox1.MaxLength = 3000;
            ServerLog.Initial();
            kcp = new KcpServer<KcpUser>(8899);
            kcp.Run(1);
            kcp.OpenHeart();
            KcpUser.WritingLog = WriteLog;
            this.timer1.Interval = 1000;
            this.timer1.Tick += (o,e) => {
                int c = queue.Count;
                for(int i=0;i<c;i++)
                {
                    var log = queue.Dequeue();
                    if(log!=null)
                    {
                        this.richTextBox1.AppendText(log.addr);
                        this.richTextBox1.AppendText("\r\n");
                        this.richTextBox1.AppendText(log.type.ToString());
                        this.richTextBox1.AppendText("\r\n");
                        this.richTextBox1.AppendText(log.condition);
                        this.richTextBox1.AppendText("\r\n");
                        this.richTextBox1.AppendText(log.stackTrace);
                        this.richTextBox1.AppendText("\r\n");
                    }
                }
            };
            this.timer1.Start();
            this.FormClosing += (o,e) => { kcp.Dispose(); };
        }
        QueueBuffer<LogData> queue = new QueueBuffer<LogData>(256);
        StringBuilder sb = new StringBuilder();
        void ReSized(object sender, EventArgs e)
        {
            this.richTextBox1.Size = ClientSize;
        }
        public void WriteLog(KcpUser kcp, LogData log)
        {
            log.addr = kcp.endpPoint.ToString();
            queue.Enqueue(log);
        }
    }
}
